package com.bbkb.quartz.controller;

import com.bbkb.common.exception.BaseException;
import com.bbkb.common.page.PageResult;
import com.bbkb.common.vo.Result;
import com.bbkb.quartz.dto.SysJobDTO;
import com.bbkb.quartz.service.ISysJobService;
import org.quartz.CronExpression;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 调度任务信息操作处理
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/admin/sysJob")
public class SysJobController {

    @Autowired
    private ISysJobService sysJobService;

    @RequestMapping("/index")
    public String index() {
        return "/admin/sysJob/sysJob";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Result list(SysJobDTO job) throws BaseException {
        PageResult<SysJobDTO> page = sysJobService.queryPage(job);
        return Result.success(page.getTotal(), page.getList());
    }


    @RequestMapping("/remove")
    @ResponseBody
    public Result remove(Long[] ids) throws BaseException, SchedulerException {
        sysJobService.deleteByIds(ids);
        return Result.success();
    }

    @RequestMapping("/detail")
    public Result detail(Long id) throws BaseException {
        SysJobDTO sysJob = sysJobService.getSysJob(id);
        return Result.success(sysJob);
    }

    /**
     * 任务调度状态修改
     */
    @RequestMapping("/changeStatus")
    @ResponseBody
    public Result changeStatus(SysJobDTO sysJobDTO) throws BaseException {
        sysJobService.updateSysJob(sysJobDTO);
        return Result.success();
    }


    /**
     * 任务调度立即执行一次
     */
    @RequestMapping("/run")
    @ResponseBody
    public Result run(Long id) throws SchedulerException {
        sysJobService.run(id);
        return Result.success();
    }

    /**
     * 新增保存调度
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result addSave(@Validated @RequestBody SysJobDTO job) throws BaseException {
        if (!CronExpression.isValidExpression(job.getCronExpression())) {
            return Result.error("cron表达式不正确");
        }
        sysJobService.addSysJob(job);
        return Result.success(job);
    }

    /**
     * 修改保存调度
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Result editSave(@Validated @RequestBody SysJobDTO job) throws BaseException {
        if (!CronExpression.isValidExpression(job.getCronExpression())) {
            return Result.error("cron表达式不正确");
        }
        sysJobService.updateSysJob(job);
        return Result.success(job);
    }

    /**
     * 校验cron表达式是否有效
     */
//    @RequestMapping("/checkCronExpressionIsValid")
//    @ResponseBody
//    public boolean checkCronExpressionIsValid(SysJob job) {
//        return sysJobService.checkCronExpressionIsValid(job.getCronExpression());
//    }
}
